package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.persistence.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    CatalogService catalogService;

    public void insertCartItem(String itemId, String username) {
        String productId = catalogService.getItem(itemId).getProductId();
        cartMapper.insertCartItem(itemId, productId, username);
    }

    public Cart getCartByUsername(String username) {
        List<CartItem> cartItems =cartMapper.getCartItemsByUsername(username);
        Cart cart = new Cart();
        for (CartItem cartItem : cartItems) {
            Item item = catalogService.getItem(cartItem.getItemId());
            cartItem.setItem(item);
            cartItem.calculateTotal();
            cart.addCartItem(cartItem);
        }
        return cart;
    }

    public void updateCart(String itemId, String username, int quantity){
        cartMapper.updateCart(itemId, username, quantity);
    }

    public void removeCartItem(String itemId, String username){
        cartMapper.removeCartItem(itemId, username);
    }

    public void removeCart(String username){
        cartMapper.removeCart(username);
    }
}
